/**
 * Created by Scc on 2017/3/28.
 */
import g from "../../global";
// import {getOrderData} from "./../../pages/montiorSearch/montiorSearch";

var _isLogin = false;

var _lastUrl = "";
function init($callback)
{
	g.addEventListener("APP_IS_LOGIN", onAppLogin_global);
	g.net.call('user/checkLogin', {}).then((d) =>
	{
		_isLogin = true;
		g.func.updateUserInfo(d)
		$callback();
	}, (error) =>
	{
		_isLogin = false;
		$callback();
	});
}

function checkLogin()
{
	var promise = new Promise((resolved, rejected) =>
	{
		g.net.call('user/checkLogin').then((d) =>
		{
			_isLogin = true;
			g.func.updateUserInfo(d)
			resolved();
		}, (err) =>
		{
			_isLogin = false;
			g.func.dealErr(err);
			rejected();
		});
	});
	return promise;
}

function initLogin($to, $next, $callBack)
{
	_lastUrl = "";
	var passUrl = ['/login', '/resetpwd', '/register', '/guide']
	if (_isLogin)
	{
		//判断当前页面是否是login页面
		if (passUrl.indexOf($to.path) >= 0)
		{
			$next("/");
		}
		else
		{
			$callBack && $callBack();
		}
	}
	else
	{
		//当前未登录
		if (passUrl.indexOf($to.path) < 0) //判断当前是否登录页
		{
			_lastUrl = $to.path;  //记录当前页地址
			var guide = $to.query.guide;
			if (guide)
			{
				$next("/guide?inviteCode=" + guide);
			}
			else
			{
				$next("/login");
			}

		}
		else
		{
			//当前在登录
			var inviteCode = $to.query.inviteCode;
			if (inviteCode && passUrl.indexOf($to.path) < 0)
			{
				$next("/login?inviteCode=" + inviteCode);
			}
			else
			{
				$next();
			}
		}
	}
}

//是否跳登录页，是否监听登录
export function logout()
{
	g.net.call("user/logout", {}).then((d) =>
	{
		_isLogin = false;
		clearLoginInfo();
		g.url = "/login";
	}, (err) =>
	{
		trace("err", err)
	});
}
window.logout = logout;

function onAppLogin_global(e)
{
	_isLogin = true;
	if (_lastUrl != "")
	{
		g.url = _lastUrl;
	}
	else
	{
		g.url = "/";
	}

}

function initNetData()
{
	var promise = new Promise((resolved, rejected) =>
	{
		g.net.call("city/getOrderCity", ($data) =>
		{
			g.data.userInfo.update({
				areaIds: $data.areaIds
			});
			resolved()
		}, (err) =>
		{
			rejected();
		})
	})
	return promise;
}

function clearLoginInfo()
{
	g.data.clear("loginTime");
	g.data.clear("userInfo");
	g.data.clear('globalParams');
	g.data.clear('skip');
	g.data.clearAll();
}

function isValid()
{
	var endDate = g.data.userInfo.validDate;
	var endList = endDate.split("-");
	var endTime = endList.join("/")
	var validDate = new Date(endTime).getTime();
	return validDate > Date.now();
}
var d = {
	init: init,
	logout: logout,
	checkLogin: checkLogin,
	initLogin: initLogin,
	isValid: isValid
};
defineProperty(d, "isLogin", () =>
{
	return _isLogin;
})

export default d;